package com.hw.kms.keyfile;

import com.crb.kms.hsm.codec.HsmSJJ1312BUtil;
import com.crb.kms.hsm.sjj1312b.codec.response.HsmEncryOrDisperseResponse;
import com.crb.kms.hsm.sjj1312b.codec.response.HsmResponse;
import com.crb.util.CrbUtil;

/**
 * 
 * @author
 * @version 1.0.0 2014-1-20 上午11:01:13
 */
public class KeyDisperse {

	/**
	 * 用CPSK分散出CPMK(芯片厂家制卡主密钥)
	 * 
	 * @param cpskIndex
	 *            卡片生产种子密钥
	 * @param seVendor
	 *            芯片厂家标识
	 * @param keyId
	 *            密钥标识
	 * @return
	 * @throws KmsException
	 */
	public static byte[] genCPMK(int cpskIndex, String seVendor, String keyId) throws KmsException {
		try {
			/*
			 * 拼装分散因子
			 */
			StringBuilder fc = new StringBuilder("00");
			fc.append(CrbUtil.string2Ascii(seVendor.substring(seVendor.length() - 3)));
			fc.append(CrbUtil.string2Ascii(keyId.substring(keyId.length() - 3)));
			fc.append("00");

			HsmEncryOrDisperseResponse resp = HsmSJJ1312BUtil.encryDataOrdisperseKey(cpskIndex,
					false, 16, fc.toString());
			if (resp.getStatus() != HsmResponse.RLT_SUCCESS) {
				return null;
			}
			return CrbUtil.hexString2Ba(resp.getData());
		} catch (Exception e) {
			throw new KmsException("genCPMK", e);
		}
	}

}
